<template>
    <div class="box">
        <div class="video_content" @contextmenu.prevent>
            <vue3-video-play
                ref="videoPlayer"
                width="100%"
                height="100%"
                v-if="videoUrl"
                :src="videoUrl"
                :poster="$baseUrl+theater_detail.episode_info[nowEpisodes - 1]?.episode_img"
                :controlBtns="controlBtns"
                :volume="0.6"
                @ended="onEnded"
                @canplay="handleCanPlay"
            />
            <div class="videoTitle" v-if="theater_detail.episode_info">第{{nowEpisodes}}集 {{ theater_detail.episode_info[nowEpisodes - 1].episode_name }}</div>
            <div class="like-share-box" v-if="theater_detail.episode_info && videoUrl">
                <div class="action-item" @click="toggleLike(1)" title="點讚">
                    <svg v-if="theater_detail.episode_info[nowEpisodes - 1].is_click == 0" t="1744957377620" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="15064" width="30" height="30"><path d="M667.786667 117.333333C832.864 117.333333 938.666667 249.706667 938.666667 427.861333c0 138.250667-125.098667 290.506667-371.573334 461.589334a96.768 96.768 0 0 1-110.186666 0C210.432 718.368 85.333333 566.112 85.333333 427.861333 85.333333 249.706667 191.136 117.333333 356.213333 117.333333c59.616 0 100.053333 20.832 155.786667 68.096C567.744 138.176 608.170667 117.333333 667.786667 117.333333z" fill="#ffffff" p-id="15065"></path></svg>    
                    <svg v-else t="1744958262648" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="18190" width="30" height="30"><path d="M667.786667 117.333333C832.864 117.333333 938.666667 249.706667 938.666667 427.861333c0 138.250667-125.098667 290.506667-371.573334 461.589334a96.768 96.768 0 0 1-110.186666 0C210.432 718.368 85.333333 566.112 85.333333 427.861333 85.333333 249.706667 191.136 117.333333 356.213333 117.333333c59.616 0 100.053333 20.832 155.786667 68.096C567.744 138.176 608.170667 117.333333 667.786667 117.333333z" fill="#d81e06" p-id="18191"></path></svg>
                    <span>{{ theater_detail.episode_info[nowEpisodes - 1].click_num || '點讚' }}</span>
                </div>
                <div class="action-item" @click="copyShareLink" title="分享">
                    <svg t="1744957489308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="17064" width="30" height="30"><path d="M940.8 349.866667L652.8 140.8c-25.6-19.2-61.866667-21.333333-89.6-6.4-32 17.066667-51.2 49.066667-51.2 83.2V277.333333C253.866667 277.333333 42.666667 488.533333 42.666667 746.666667c0 40.533333 4.266667 78.933333 14.933333 117.333333 4.266667 19.2 21.333333 32 40.533333 32 19.2 0 36.266667-12.8 40.533334-32C183.466667 695.466667 337.066667 576 512 576v59.733333c0 36.266667 19.2 68.266667 49.066667 83.2 12.8 6.4 25.6 8.533333 38.4 8.533334 17.066667 0 36.266667-6.4 51.2-17.066667L938.666667 501.333333c23.466667-17.066667 38.4-46.933333 38.4-76.8 2.133333-27.733333-10.666667-57.6-36.266667-74.666666z" fill="#ffffff" p-id="17065"></path></svg>
                    <span>{{ theater_detail.episode_info[nowEpisodes - 1].share_num || '分享'}}</span>
                </div>
            </div>
            <div class="unPay" @click="toEpisodes(nowEpisodes,null,true)" v-if="theater_detail.episode_info && theater_detail.episode_info[nowEpisodes - 1].is_pay == 0 && theater_detail.episode_info[nowEpisodes - 1].is_free == 0">
                <svg t="1745226054973" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8444" width="80" height="80"><path d="M512 85.333333c235.648 0 426.666667 191.018667 426.666667 426.666667s-191.018667 426.666667-426.666667 426.666667S85.333333 747.648 85.333333 512 276.352 85.333333 512 85.333333z m0 170.666667a42.666667 42.666667 0 0 0-42.666667 42.666667v341.333333a42.666667 42.666667 0 0 0 85.333334 0V298.666667a42.666667 42.666667 0 0 0-42.666667-42.666667z m0 554.666667a42.666667 42.666667 0 1 0 0-85.333334 42.666667 42.666667 0 0 0 0 85.333334z" fill="#FAAD14" p-id="8445"></path></svg>
                <p>點此消耗購買的集數即可觀看</p>
            </div>
        </div>
        <div class="video_detail">
            <div class="header">
                <div class="img_box">
                    <img :src="$baseUrl+theater_detail.theater_img" alt="">
                </div>
                <div class="title">
                    <p>{{ theater_detail.theater_name }}</p>
                    <div class="tags">
                        <span v-if="theater_detail.theater_tag" v-for="tag in theater_detail.theater_tag.split(',')" :key="tag">{{ tag }}</span>
                    </div>
                    <div class="tip">{{theater_detail.sum_episode}}集全</div>
                </div>
            </div>
            <div class="expandable" :style="!isShowExpander ? 'margin-bottom: 20px;' : ''">
				<div class="bui-expander-content" ref="content_introduce">
					<div class="multi-line-text" ref="multiLineText">
						{{ theater_detail.desc }}
					</div>
				</div>
				<div v-if="isShowExpander" class="bui-expander-switch" @click="switch_introduce_fn"><span ref="text_introduce">{{$t('expand')}}</span><i ref="i_introduce"></i></div>
			</div>
            <div class="paybox" v-if="hasPay && theater_detail.free_type == 2">
                <div class="payVip" @click="changeIsShow('all')">購買整部</div>
                <div class="payVip2" @click="changeIsShow('batch')">批量購買</div>
            </div>
            
            <el-tabs v-model="activeTab" class="elTab">
                <el-tab-pane
                    v-for="(group, index) in episodeGroups"
                    :key="index"
                    :label="`${group.start}-${group.end}`"
                    :name="`${index}`"
                >
                <div class="tag_content">
                    <div @click="toEpisodes(ep)" :class="{nowEpisodes:nowEpisodes == ep}" class="tag_content_item" v-for="ep in group.episodes" :key="ep">
                        <span>{{ ep }}</span>
                        <div class="tag" v-if="theater_detail.episode_info[ep-1].is_free == 1 && theater_detail.free_episode >= ep && theater_detail.episode_info[ep-1].is_pay != 1">免費</div>
                        <div class="tagVip" v-if="theater_detail.episode_info[ep-1].is_free !== 1 && theater_detail.episode_info[ep-1].is_free !== 2 && theater_detail.episode_info[ep-1].is_pay != 1">付費</div>
                        <div class="tagVip isPay" v-if="theater_detail.episode_info[ep-1].is_pay == 1">已解鎖</div> 
                    </div>
                </div>
                </el-tab-pane>
            </el-tabs>
            <div class="RecommendVideo">
                <RecommendVideo :dataList="theaterBannerList.filter(item=>item.id != theater_id)"/>
            </div>
        </div>
        <SandPayBox ref="SandPayBoxRef" :getUserInfo="getUserInfo" :free_type="theater_detail.free_type" :expireInitEp="expireInitEp" :episode_info="theater_detail.episode_info" :freeCount="freeCount" :isExpire="isExpire" :getTheateList="getTheateList" :totalEpisodes="totalEpisodes" :free_episode="theater_detail.free_episode" :payCount="payCount" :payEp="payEp" :isShow="isShow" :changeIsShow="changeIsShow" :payType="payType" :nowEpisodes="nowEpisodes" :episode_money="theater_detail.episode_money" :rebate="theater_detail.rebate"/>
        <div class="payBox" v-if="isPaydialog" style="padding-top: 7px;">
            <div class="close2" @click="isPaydialog = false"></div>
            <h2 class="title" style="padding-left: 10px;">解鎖本集(第{{ payEp }}集)</h2>
            <div class="form" style="margin-top: 20px;">
                <div class="price">確認要消耗1集已購買的劇集解鎖本集嗎？</div>
                <span>剩餘可用集數：{{ user_info.episode_num }}</span>
                <span>注意：解鎖有效期為15天</span>
                <button @click="Unlock">確認</button>
            </div>
        </div>
        <div class="masker" v-if="isPaydialog"></div>
    </div>
</template>

<script setup>
import axios from '@/utils/api'
import vue3VideoPlay from 'vue3-video-play';
import 'vue3-video-play/dist/style.css';
import switch_bar from "@/hooks/switch_bar_video"
import SandPayBox from "@/components/SandPayBox/index.vue"
import { useUserInfoStore } from '@/store/modules/user_info/index';
import RecommendVideo from "@/components/recommendVideo/index.vue"
const user_infoStore = useUserInfoStore();
let user_info = reactive(user_infoStore.userInfo)
const userid = user_info.id
const route = useRoute();
const router = useRouter();
const theater_id = route.query.id
const episode = route.query.episode
const theater_detail = ref({})
const payCount = ref(0)
const freeCount = ref(0)
const videoUrl = ref('')
const isConnect = ref(false)
const isExpire = ref(false) //免费集数是否过期
const hasPay = ref(false) //最后一集是否购买，是否显示购买的按钮
const isPaydialog = ref(false)
const isTimestampExpired = (unixTimestamp)=>{
  const targetTime = unixTimestamp * 1000 // 转为毫秒
  const now = Date.now()
  return now > targetTime
}

const getUserInfo = async () =>{
    const data = {
        user_id:user_info.id,
    }
    console.log(1111111111111);
    
    const list = await axios.post('/getUserInfo',data)
    console.log(222222222222222);
    Object.assign(user_info, list.data.user_info)
    user_infoStore.setUserinfo(list.data.user_info)
}


const getTheateList = async () => {
    const res = await axios.get(`/theaterDetail?theater_id=${theater_id}&user_id=${userid}`)
    if (res.code == 200) {
        if(res.data.sum_episode == 0){
            ElMessage.error('該劇本暫無內容')
            setTimeout(() => {
                window.top.location.href = '//' + window.location.hostname + '/#/home/SandSculpture' 
            }, 1500);
            return
        }
        theater_detail.value = res.data
        if(res.data.sum_episode !== theater_detail.value.episode_info.length){
            totalEpisodes.value = theater_detail.value.episode_info.length
        }else{
            totalEpisodes.value = res.data.sum_episode
        }
        payCount.value = theater_detail.value.episode_info.filter(item => item.is_pay === 1).length;
        freeCount.value = theater_detail.value.episode_info.filter(item => item.is_free == 1 && item.is_pay == 0).length
        hasPay.value = theater_detail.value.episode_info[theater_detail.value.episode_info.length-1].is_pay == 0 && theater_detail.value.episode_info[theater_detail.value.episode_info.length-1].is_free == 0
        console.log(theater_detail.value.episode_info[theater_detail.value.episode_info.length-1].is_pay,'is_pay');
        
        window.top.document.title = theater_detail.value.theater_name;

        if (!theater_detail.value.episode_info[0]?.free_end_time || isTimestampExpired(theater_detail.value.episode_info[0].free_end_time)) {
            isExpire.value = true
            console.log(isExpire.value,isTimestampExpired(theater_detail.value.episode_info[0].free_end_time),!theater_detail.value.episode_info[0]?.free_end_time || isTimestampExpired(theater_detail.value.episode_info[0].free_end_time),'33333');
        }
        console.log(isExpire.value,'22222222');
        
        if(!import.meta.env.DEV && !isConnect.value){
            connectSocket()
            isConnect.value = true
        }
        
        nextTick(()=>{
            setExpander()
        })
    } else {
        ElMessage.error(res.message)
    }
}
getTheateList()

const init_theater_progress = ref(0)
let inter = null

const getUserWatchLog = async () => {
    const res = await axios.get(`/userWatchLog?theater_id=${theater_id}&user_id=${userid}`)
    if (res.code == 200) {
        const hisEpisodes = res.data.data.find(item => item.theater_id == theater_id)
        console.log('hisEpisodes', hisEpisodes,res.data.data);
        if(hisEpisodes){
            nowEpisodes.value = hisEpisodes.theater_progress
            init_theater_progress.value = hisEpisodes.episode_progress
        }else{
            if(theater_detail.value.episode_info[episode - 1]?.is_free == 1){
                nowEpisodes.value = episode
                init_theater_progress.value = 0
            }
            
        }
        
        getInitVideo()
        console.log(theater_detail.value.episode_info[nowEpisodes.value - 1],nowEpisodes.value,'0000000000');
        
        if(theater_detail.value.episode_info[nowEpisodes.value - 1]?.is_free == 1 || theater_detail.value.episode_info[nowEpisodes.value - 1].is_pay == 1){
            inter = setInterval(() => {
                const watch_time = document.getElementById('dPlayerVideoMain').currentTime
                const episode_id = theater_detail.value.episode_info[nowEpisodes.value - 1].id
                const data = {
                    user_id: user_info.id,
                    theater_id,
                    episode_id,
                    episode_index: nowEpisodes.value,
                    watch_time,
                    ControllerName:'WatchTheater'
                }
                socket.value.send(JSON.stringify(data)); 
            }, 8000);
        }
        
    } else {
        ElMessage.error(res.message)
    }
}

const setVh = ()=>{
    let vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
}

const controlBtns = [
  'audioTrack', 'quality', 'speedRate', 'volume', 'pageFullScreen', 'fullScreen'
];


const isShowExpander = ref(false)
const multiLineText = ref(null) //描述查看更多
const setExpander = () =>{
    console.log(multiLineText.value,'multiLineText');
    
    const heightPx = multiLineText.value.getBoundingClientRect().height
    if(heightPx > 104){
        isShowExpander.value = true
    }
    console.log('元素高度是：', heightPx);

}


onMounted(() => {
    setVh()
});

onBeforeUnmount(()=>{
    clearInterval(inter)
    inter = null;
})

const initVideo = () => {
    const textMap = {
      '播放': '播放',
      '暂停': '暫停',
      '全屏': '全螢幕',
      '退出全屏': '退出全螢幕',
      '選集': '選集',
      '靜音': '靜音',
      '音量': '音量',
      '上一集': '上一集',
      '下一集': '下一集',
      '网页全屏': '網頁全螢幕',
    };
    Object.entries(textMap).forEach(([zh, zh_tw]) => {
      document.querySelectorAll('*').forEach(el => {
        if (el.innerText === zh) {
          el.innerText = zh_tw;
        }
      });
    });

    
    const toolBar0 = document.querySelectorAll('.d-tool-bar')[0];
    console.log(toolBar0,'toolBar0');
    
    const div2 = document.createElement('div');
    div2.title = '下一集'
    div2.innerHTML = '<svg t="1744011963153" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2791" width="20" height="20"><path d="M768 535.8592L128.7168 919.3472A51.2 51.2 0 0 1 51.2 875.52V90.4192A51.2 51.2 0 0 1 128.7168 46.4896L768 430.08V76.8a76.8 76.8 0 0 1 153.6 0v819.2a76.8 76.8 0 0 1-153.6 0V535.8592z" fill="#ffffff" p-id="2792"></path></svg>'
    div2.addEventListener('click', nextEp);
    Object.assign(div2.style, {
        position: 'relative',
        height: '100%',
        cursor: 'pointer',
        textAlign: 'center',
        padding: '0 8px',
        display: 'flex',
        alignItems: 'center',
        fontSize: '13px',
        background: 'none',       // 可选：去除默认按钮背景
        border: 'none',           // 可选：去除默认按钮边框
        color: '#fff'             // 可选：文字颜色，可根据主题调整
    });
    toolBar0.appendChild(div2);
}

let switch_status_introduce = ref(true) //展开收起状态
const content_introduce = ref() //文本容器
const text_introduce = ref() //展开收起按钮
const i_introduce = ref() //图标按钮
const switch_introduce_fn = () => { //点击函数
    switch_bar(switch_status_introduce, content_introduce, text_introduce, i_introduce)
}

const totalEpisodes = ref(0)

// 每个 Tab 显示多少集
const perTab = 50

// 当前激活的 tab
const activeTab = ref('0')

// 计算分组
const episodeGroups = computed(() => {
  const groups = []
  const total = totalEpisodes.value

  const tabsCount = Math.ceil(total / perTab)

  for (let i = 0; i < tabsCount; i++) {
    const start = i * perTab + 1
    const end = Math.min((i + 1) * perTab, total)
    const episodes = []
    for (let j = start; j <= end; j++) {
      episodes.push(j)
    }
    groups.push({ start, end, episodes })
  } 

  console.log('总集数:', totalEpisodes.value)
  console.log('每页数量:', perTab)
  return groups
})

const nowEpisodes = ref(1)
const isShow = ref(false)
const payType = ref('one')
const SandPayBoxRef = ref()
const changeIsShow = (type,isTrue)=>{
    isShow.value = !isShow.value
    console.log(isShow.value,payType.value);
    
    if(type == 'pack'){
        payType.value = type
        return
    }
    if(!isShow.value){
        payEp.value = null
    }else{
        if(!isTrue){
            let num = 0
            const detailList = JSON.parse(JSON.stringify(theater_detail.value.episode_info)).reverse()
            for (let i = 0; i < detailList.length; i++) {
                if(detailList[i].is_pay == 0 && detailList[i].is_free == 0){
                    num++ 
                    if(i == detailList.length-1){
                        expireInitEp.value = detailList[i].index
                        break
                    }
                }else{
                    expireInitEp.value = detailList[i].index+1
                    break
                }
            }
        }
        
        if(type == 'all'){
            console.log(totalEpisodes.value,theater_detail.value.free_episode,payCount.value);
            if(isExpire.value){
                let num = 0
                const detailList = JSON.parse(JSON.stringify(theater_detail.value.episode_info)).reverse()
                for (let i = 0; i < detailList.length; i++) {
                    if(detailList[i].is_pay == 0 && detailList[i].is_free == 0){
                        num++ 
                    }else{
                        break
                    }
                }
                SandPayBoxRef.value.count = num
            }else{
                SandPayBoxRef.value.count = totalEpisodes.value - freeCount.value - payCount.value
            }
        }else{
            SandPayBoxRef.value.count = 1 //购买本集重置数量为1
        }
    }
    payType.value = type
    
    
}


const onEnded = () => {
  console.log("播放完一集了");

  // 如果还有下一集就自动播放
  if (nowEpisodes.value < totalEpisodes.value && !isShow.value) {
    nowEpisodes.value++;
    toEpisodes(nowEpisodes.value,true)
  }
};

const nextEp = () => {
  console.log("下一集");

  // 如果还有下一集就自动播放
  if (nowEpisodes.value < totalEpisodes.value) {
    nowEpisodes.value++;
    toEpisodes(nowEpisodes.value,true)
  }else{
    ElMessage.warning('已經是最後一集了')
  }
};


const payEp = ref(null)
const videoPlayer = ref(null);
const expireInitEp = ref(0)

const toEpisodes = (ep = nowEpisodes.value,isNext,isUnPay)=>{
    console.log(ep,theater_detail.value.free_episode + payCount.value);
    
    
    if(theater_detail.value.episode_info[ep - 1].is_free == 0 && theater_detail.value.episode_info[ep - 1].is_pay == 0){
        console.log(ep - theater_detail.value.free_episode + payCount.value);

        console.log('判断是否还有集数，有则弹出是否解锁，没有就弹出购买框',user_info.episode_num);
        if(user_info.episode_num > 0){
            console.log('弹出购买款');
            isPaydialog.value = true
            payEp.value = ep
        }else if(theater_detail.value.free_type == 1){
            if(!isUnPay){
                ElMessage.warning('剩餘可用集數不足，請先購買集數')
            }
            changeIsShow('pack')
        }else{
            if(!isUnPay){
                ElMessage.warning('剩餘可用集數不足，請先購買集數')
            }
            if(!isExpire.value){ //是否过期
                console.log(ep,freeCount.value,payCount.value,ep - freeCount.value - payCount.value,9999999);
                
                if(ep - freeCount.value - payCount.value > 1){ //购买大于1集
                    changeIsShow('batch')
                    SandPayBoxRef.value.count = ep - freeCount.value - payCount.value
                }else{ //购买1集
                    changeIsShow('payOne')
                }
            }else{
                let num = 0
                const detailList = theater_detail.value.episode_info.slice(0, ep-1).reverse()
                for (let i = 0; i < detailList.length; i++) {
                    if(detailList[i].is_pay == 0 && detailList[i].is_free == 0){
                        num++
                        if(i == detailList.length-1){
                            expireInitEp.value = detailList[i].index
                            break
                        }
                    }else{
                        expireInitEp.value = detailList[i].index+1
                        break
                    }
                }
                console.log(expireInitEp.value,'11111111');
                
                if(ep < expireInitEp.value){
                    expireInitEp.value = 1;
                }
                console.log(expireInitEp.value,'222222222');
                if(num >= 1){ //购买大于1集
                    changeIsShow('batch',true)
                    SandPayBoxRef.value.count = num + 1
                }else{ //购买1集
                    changeIsShow('payOne')
                }
            }
            
            
        }
        
        
        payEp.value = ep
        
        if(isNext){
            nowEpisodes.value--
            clearInterval(inter)
            inter = null;
            console.log('清除定时器');
        }
        
        
        return
    }
    nowEpisodes.value = ep
    getInitVideo()
    if(!inter){
        inter = setInterval(() => {
            const watch_time = document.getElementById('dPlayerVideoMain').currentTime
            const episode_id = theater_detail.value.episode_info[nowEpisodes.value - 1].id
            const data = {
                user_id: user_info.id,
                theater_id,
                episode_id,
                episode_index: nowEpisodes.value,
                watch_time,
                ControllerName:'WatchTheater'
            }
            socket.value.send(JSON.stringify(data)); 
        }, 8000);
    }
    // videoPlayer.value.play()
}

const nowRate = ref(1) //当前倍速
const ratechange = ()=>{
    console.log('当前倍速为:', document.getElementById('dPlayerVideoMain').playbackRate);
    nowRate.value = document.getElementById('dPlayerVideoMain').playbackRate
}

const socket = ref(null);
const isInitVideo = ref(true)
const isSetVolume = ref(false) //第一次进入页面设置音量
const connectSocket = ()=>{
    socket.value = new WebSocket(`wss://${window.location.hostname.replace(/^www\./, '')}/ws?type=web&user_id=${user_info.id}&username=${user_info.username}`);
    socket.value.onmessage = (event) => {
        const data = JSON.parse(event.data);
		console.log("收到消息：",event);
        if(data.Code == 0 && (data.Status == 'Message' || data.Status == 'pay')){
            console.log('設置视频链接');
            
            if(videoUrl.value){
                document.getElementById('dPlayerVideoMain').playbackRate = nowRate.value
            }
            videoUrl.value = data.Message
            // if(init_theater_progress.value){
            //     document.getElementById('dPlayerVideoMain').addEventListener('loadedmetadata', function() {
            //         console.log(videoPlayer.value,document.getElementById('dPlayerVideoMain'));
            //         document.getElementById('dPlayerVideoMain').currentTime = init_theater_progress.value
            //         init_theater_progress.value = null
            //     });
                
            // }
            if(isInitVideo.value){
                nextTick(()=>{
                    isInitVideo.value = false
                    console.log(videoPlayer.value,11111);
                    
                        if(!hasUserInteracted){
                            document.getElementById('dPlayerVideoMain').volume = 0
                            document.querySelectorAll('.d-slider__bar')[1].style.height = 0
                            document.querySelector('.volume-text-size').innerHTML = '0%'
                            document.querySelectorAll('.d-icon')[5].classList.add('icon-volume-mute')
                        }else if(!isSetVolume.value){
                            document.getElementById('dPlayerVideoMain').volume = 0.6
                            document.querySelectorAll('.d-slider__bar')[1].style.height = "60%"
                            document.querySelector('.volume-text-size').innerHTML = '60%'
                            document.querySelectorAll('.d-icon')[5].classList.add('icon-volume-up')
                            document.querySelectorAll('.d-icon')[5].classList.remove('icon-volume-mute')
                            isSetVolume.value = true
                        }
                        
                    
                    
                    videoPlayer.value.play()
                    document.getElementById('dPlayerVideoMain').removeEventListener('ratechange', ratechange);
                    document.getElementById('dPlayerVideoMain').addEventListener('ratechange', ratechange);
                })
            }
            
        }else if (data.Code == 0 && data.Status == 'log') { //解锁成功
            console.log('解锁视频');
            ElMessage.success('解鎖成功')
            videoUrl.value = data.Message
            nowEpisodes.value = payEp.value
            isPaydialog.value = false
            getTheateList()
            getUserInfo()
            nextTick(()=>{
                videoPlayer.value.play()
            })

            console.log(inter,'定时器inter');
            
            if(!inter){
                console.log(inter,'设置定时器inter');
                inter = setInterval(() => {
                    const watch_time = document.getElementById('dPlayerVideoMain').currentTime
                    const episode_id = theater_detail.value.episode_info[nowEpisodes.value - 1].id
                    const data = {
                        user_id: user_info.id,
                        theater_id,
                        episode_id,
                        episode_index: nowEpisodes.value,
                        watch_time,
                        ControllerName:'WatchTheater'
                    }
                    socket.value.send(JSON.stringify(data)); 
                }, 8000);
            }
        }
    }
    socket.value.onopen = () => {
		console.log("WebSocket连接已建立");
        getUserWatchLog()
        
        
    }
    socket.value.onclose = () => {
		console.log("WebSocket连接已关闭");
	};
}

const handleCanPlay = () => {
  if (init_theater_progress.value !== 0) {
    const videoEl = document.getElementById('dPlayerVideoMain')
    if (videoEl) {
      videoEl.currentTime = init_theater_progress.value
      console.log(`跳转到进度：${init_theater_progress.value}s`)
      init_theater_progress.value = 0
    } else {
      console.warn('视频元素未找到')
    }
    nextTick(()=>{
        initVideo()
    })
  }
}


const getInitVideo = ()=>{ //获取当前集数视频url
    console.log(nowEpisodes.value,theater_detail.value.episode_info[nowEpisodes.value - 1]);
    isInitVideo.value = true
    const initData = {
        user_id: user_info.id,
        theater_id,
        episode_id:theater_detail.value.episode_info[nowEpisodes.value - 1].id,
        episode_index: nowEpisodes.value,
        watch_time: 0,
        ControllerName:'WatchTheater'
    }
    socket.value.send(JSON.stringify(initData)); 
}

const copyShareLink = () => {
  const url = window.top.location.href+'&episode='+nowEpisodes.value
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('分享鏈接已復製')
    toggleLike(2)
  }).catch(() => {
    ElMessage.error('復製失敗，請手動複製')
  })
}

const toggleLike = async (type)=>{ //1点赞 2分享
    const episode_id = theater_detail.value.episode_info[nowEpisodes.value - 1].id
    const res = await axios.get(`/clickEpisode?operate=${type}&user_id=${userid}&episode_id=${episode_id}`)
    if (res.code == 200 && type == 1) {
        // ElMessage.success(res.message)
        getTheateList()
    } 
}

let hasUserInteracted = false;

const handleUserInteraction = () => {
  if (!hasUserInteracted) {
    hasUserInteracted = true;
    console.log('✅ 用户已交互');

    // 可以移除监听器以优化性能
    removeUserInteractionListeners();
  }
};

const addUserInteractionListeners = () => {
  ['click', 'keydown', 'touchstart', 'scroll'].forEach(evt => {
    window.addEventListener(evt, handleUserInteraction, { once: true });
  });
};

const removeUserInteractionListeners = () => {
  ['click', 'keydown', 'touchstart', 'scroll'].forEach(evt => {
    window.removeEventListener(evt, handleUserInteraction);
  });
};

// 初始化监听
addUserInteractionListeners();

const theaterBannerList = ref([])
const getTheaterBannerList = async () => {
    const res = await axios.get('/theaterBannerList?limit=99')
    if (res.code == 200) {
        theaterBannerList.value = res.data.data
    } else {
        ElMessage.error(res.message)
    }
}
getTheaterBannerList()


const Unlock = ()=>{
    console.log('解鎖');
    const episode_id = theater_detail.value.episode_info[payEp.value - 1].id
    const data = {
        user_id: user_info.id,
        theater_id,
        episode_id,
        episode_index: payEp.value,
        ControllerName:'WatchTheater'
    }
    socket.value.send(JSON.stringify(data)); 
}
</script>

<style lang="less" scoped>
@main: #ff9e3d;
@text: #333;
.box{
    user-select: none;
    display: flex;
    height: calc(var(--vh, 1vh) * 100 - 80px);
    .video_content{
        height: 100%;
        flex: 1;
        position: relative;
        overflow: hidden;
        background-color: black;
        .unPay{
			width: 100%;
			height: 100%;
			background-color: #000;
			position: absolute;
			top: 0;
			left: 0;
			z-index: 999;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
			text-decoration: underline;
            display: flex;
            flex-direction: column;
            p{
                cursor: pointer;
                margin-top: 10px;
            }
            p:hover{
                color: #c8c8c8;
            }
		}
        .videoTitle{
            position: absolute;
            top: -70px;
            left: 0;
            padding: 2%;
            box-sizing: border-box;
            z-index: 999;
            font-size: 20px;
            color: white;
            width: 100%;
            background:linear-gradient(to bottom, rgba(0,0,0,0.3), rgba(0,0,0,0));
            transition: all .3s;
        }
        .like-share-box {
            display: flex;
            flex-direction: column;
            justify-content: center;
            gap: 20px;
            margin-top: 10px;
            align-items: center;
            position: absolute;
            right: 20px;
            bottom: 100px;
            z-index: 9;

            .action-item {
                display: flex;
                align-items: center;
                justify-content: center;
                flex-direction: column;
                cursor: pointer;
                font-size: 14px;
                color: rgb(199, 199, 199);

                &:hover {
                    filter: brightness(1.5);
                }
                
            }
            .action-item:first-child{
                svg{
                    transition: all .3s;
                    &:active {
                        transform: scale(0.8);
                    }
                }
            }
        }
    }
    .video_content:hover{
        .videoTitle{
            top: 0 !important;
        }
        
    }
    .video_detail{
        width: 340px;
        overflow: auto;
        background-color: #232426;
        padding: 13px;
        box-sizing: border-box;
        .RecommendVideo {
			margin-top: 20px;
		}
        .header{
            display: flex;
            margin-top: 5px;
            .img_box{
                height: 160px;
                display: flex;
                margin: 0;
                img{
                    border-radius: 5px;
                    object-fit: cover;
                    width: 130px;
                }
            }
            .title{
                margin-left: 10px;
                p{
                    font-weight: bold;
                    text-overflow: ellipsis;
                    white-space: normal;
                    overflow: hidden;
                    -webkit-line-clamp: 2;
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    color: white;
                    font-size: 18px;
                }
                .tags{
                    height: 58px;
                    overflow: hidden;
                    display: flex;
                    flex-wrap: wrap;
                    align-items: center;
                    flex-direction: row;
                    justify-content: flex-start;
                    row-gap: 10px;
                    margin-top: 12px;
                    span{
                        align-items: center;
                        background-color: #ffffff1a;
                        border-radius: 4px;
                        color: #fffffff2;
                        display: flex;
                        flex-shrink: 0;
                        font-size: 12px;
                        height: 20px;
                        margin-right: 8px;
                        padding: 2px 6px;
                        margin-left: 0;
                    }
                }
                .tip{
                    color: #fff9;
                    font-size: 12px;
                    margin-top: 12px;
                }
                
            }
        }
        .paybox{
            margin-top: 15px;
            display: flex;
            .payVip{
                background: linear-gradient(to right, #fce7b4, #fab660);
                border-radius: 30px 0 0 30px;
                text-align: center;
                padding: 8px 0;
                color: #df7b09;
                font-weight: bold;
                cursor: pointer;
                margin: 0;
                width: 50%;
            }
            .payVip2{
                background: linear-gradient(to right,#fab660, #fce7b4);
                border-radius: 0 30px 30px 0;
                text-align: center;
                padding: 8px 0;
                color: #df7b09;
                font-weight: bold;
                cursor: pointer;
                margin: 0;
                width: 50%;
                border-left: 1px solid #ababab45;
            }
            .payVip:hover,.payVip2:hover{
                filter: brightness(1.05);
            }
        }
        
        .expandable {
            margin-top: 15px;
			.bui-expander-content {
				overflow: hidden;
				transition: max-height .5s ease;
				max-height: 6.5em;

				.multi-line-text {
					color: #fff9;
					padding-right: 1px;
					white-space: pre-wrap;
					line-height: 20px;
                    font-size: 14px;
				}
			}

			.bui-expander-switch {
				text-align: right;
				color: #ffffff;
				cursor: pointer;
				line-height: 2;
			}

			i {
				background-repeat: no-repeat;
				background-size: contain;
				background-image: url();
				display: inline-block;
				vertical-align: middle;
				width: 14px;
				height: 14px;
				margin-left: 5px;
                filter: grayscale(1) brightness(5);
			}

			.switch-icon-down {
                filter: grayscale(1) brightness(5);
				background-image: url() !important;
			}
		}
        ::v-deep .el-tabs__item,::v-deep .el-tabs__content {
            color: #ffffff; /* 默认字体颜色 */
        }
        ::v-deep .el-tabs__item.is-active {
            color: #409EFF; /* 选中时的字体颜色 */
        }
        .elTab{
            margin-top: 15px;
        }
        .tag_content{
            grid-gap: 8px;
            box-sizing: border-box;
            display: grid;
            grid-template-columns: repeat(5, 55px);
            width: 100%;
            .tag_content_item{
                background-color: #ffffff0a;
                background-image: url();
                background-size: contain;
                border-radius: 8px;
                color: #ffffffe6;
                font-size: 18px;
                height: 48px;
                overflow: hidden;
                width: 55px;
                cursor: pointer;
                position: relative;
                span{
                    display: inline-block;
                    font-size: 18px;
                    height: 48px;
                    line-height: 48px;
                    text-align: center;
                    width: 55px;
                }
                .tag {
                    background: linear-gradient(to right, #adf4cc, #60e8a1);
                    display: inline-block;
                    position: absolute;
                    right: 0;
                    top: 0;
                    padding: 1px 5px;
                    border-radius: 0 8px 0 8px;
                    font-size: 9px;
                    color: #082818;
                    font-weight: bold;
                }

                .tagVip {
                    background: linear-gradient(to right, #fce7b4, #fab660);
                    display: inline-block;
                    position: absolute;
                    right: 0;
                    top: 0;
                    padding: 1px 5px;
                    border-radius: 0 8px 0 8px;
                    font-size: 9px;
                    color: #082818;
                    font-weight: bold;
                }
                .isPay{
                    background: linear-gradient(to right, #b4e7fc, #60cdfa);
                }
            }
            .nowEpisodes{
                color: #54bdff;
                background-repeat: no-repeat;
                background-size: 328%;
                background-position: center;
                background-image: url(https://www.yyfuns.com/static/tvg_episode.png);
            }
            .nowEpisodes::after{
                background-image: url();
                height: 8px;
                width: 10px;
                bottom: 6px;
                content: "";
                left: 6px;
                position: absolute;
                filter: hue-rotate(68deg);
            }
            .tag_content_item:hover{
                background-repeat: no-repeat;
                background-size: 328%;
                background-position: center;
                background-image: url(https://www.yyfuns.com/static/tvg_episode.png);
            }
        }
        

    }
}


.payBox {
  width: 380px;
  padding: 15px 24px;
  padding-top: 35px;
  border-radius: 15px;
  // background: linear-gradient(1deg, #ffeeb8b0, #e6c982e0);
  backdrop-filter: blur(16px);
  background-image: url("");
  background-size: cover;
  background-position: right;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1001;
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: popIn 0.3s ease-out;

  header {
    // background:linear-gradient(to bottom, #a56e40, #fffaf3);
    width: 100%;
    position: absolute;
    top: 0;
    border-radius: 15px 15px 0 0;
    padding: 8px 0 20px;
  }

  .discount-rules {
    margin-top: 30px;
    font-size: 15px;
    color: #434343;
    margin-left: 0px;
  }

  .discount-rules ul {
    margin: 5px 0;
    list-style-type: disc;
  }

  .discount-rules strong {
    color: #e91e63;
  }

  p {
    font-size: 16px;
  }

  .bg_img {
    position: absolute;
    right: 17px;
    bottom: 15px;
    // filter: invert(1) brightness(30);
  }
  
  .title {
        font-size: 22px;
        font-weight: 600;
        color: @text;
        text-align: left;
        padding-left: 23px;
        color: #745d4b;
        margin-top: 3px;
    }
    .form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
  margin-top: 30px;
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(16px);
  box-shadow: 0 10px 30px #b5b5b540;
  border-radius: 12px;
  padding: 15px 0;
  span{
    color: #9d7c57;
    font-size: 13px;
  }
  .choose{
    display: flex;
    align-items: center;
    :deep(.el-select__wrapper) {
      height: 36px;
      border-radius: 4px !important;
    }
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-left: 20px;
    color: black;
  }

  label {
    font-size: 15px;
    color: #ff9e3d;

    // margin-left: 100px;
    span {
      color: black;
    }
  }

  .number {
    display: flex;
    align-items: center;
    justify-content: center;

    span {
      margin-left: 21px;
      margin-right: 0;
    }
  }

  input {
    margin: 0;
    width: 40px;
    padding: 1px 11px;
    border-radius: 32px;
    border: 1px solid #ddd;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.9);
    transition: all 0.3s ease;
    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
    color: black;

    &:focus {
      border-color: @main;
      box-shadow: 0 0 0 3px rgba(255, 158, 61, 0.2);
      outline: none;
    }
  }

  .price {
    font-size: 16px;
    color: #9b590e;

    span {
      color: @main;
      font-size: 19px;
    }

    .strike {
      position: relative;
      display: inline-block;
      color: #999;
    }

    .strike::after {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      top: 50%;
      height: 2px;
      /* 控制粗细 */
      background-color: currentColor;
      transform: translateY(-50%);
      pointer-events: none;
      color: #df7b09;
    }
  }

  button {
    width: 90%;
    padding: 8px;
    font-size: 16px;
    font-weight: bold;
    color: #df7b09;
    background: linear-gradient(119deg, #fdbc6a, #fce7b4);
    border: none;
    border-radius: 45px;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 4px 14px rgba(255, 158, 61, 0.3);
    margin-top: 5px;

    &:hover {
      filter: brightness(1.05);
      transform: translateY(-1px);
    }

    &:active {
      transform: scale(0.97);
    }
  }
}
}
.masker {
    background: rgba(0, 0, 0, 0.5);
    position: fixed;
    inset: 0;
    z-index: 1000;
}
</style>